<template>
  <v-container>
    <v-card-actions>
      <v-btn color="primary" @click.stop="onAddNew"
        >新增栏目</v-btn
      >
    </v-card-actions>
    <v-treeview
      ref="treeview"
      v-model="selectedItem"
      :items="items"
      :active.sync="activeItems"
      :load-children="fetchChildren"
      activatable
      hoverable
      rounded
      item-key="id"
      return-object
    >
      <template v-slot:prepend="{ open }">
        <v-icon>{{ open ? "mdi-folder-open" : "mdi-folder" }}</v-icon>
      </template>
      <template v-slot:label="{ item }">
        <span>{{ item.category_name }}</span>
      </template>
      <template v-slot:append="{ item, active }">
          <v-btn v-if="active" color="primary" small @click.stop="renameNode(item)">编辑</v-btn>
          <v-btn v-if="active" color="primary" small @click.stop="addChildrenNode(item)">新增子栏目</v-btn>
          <v-btn v-if="active" color="primary" small @click.stop="deleteNode(item)">删除该栏目</v-btn>
      </template>
    </v-treeview>
    <v-dialog v-model="showNodeEditDialog" light color="grey">
      <v-card>
        <!-- <v-card-title>
          在{{currentSelectNode.name}}下
        </v-card-title> -->
        <v-card-text>
          <v-form>
            <v-text-field
              v-model="curEditNode.category_name"
              required
              placeholder="类别名称"
            >
            </v-text-field>
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-btn
            color="primary"
            rounded
            @click.stop="showNodeEditDialog = false"
            >关闭</v-btn
          >
          <v-spacer></v-spacer>
          <v-btn color="primary" rounded @click.stop="confirmEdit">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script>
// 文章类别
// emit update:activeNode
  import { ArticleCategory } from "@/store/models/article"
  import { TreeViewHelper } from "@/store/models/treeview_helper"
  import merge from "lodash/merge"

  export default {
    name: "ArticleCategory",
    data: () => ({
      items: [],
      selectedItem: [],
      activeItems: [],      
      curEditNode: new ArticleCategory(),
      showNodeEditDialog: false,
    }),
    watch: {
      activeItems(items) {
        this.$emit("update:activeNode", items[0])
      },
      "currentSelectNode.id": function (node_id, old_val) {
        // 手工实现点击节点后自动去open该节点，即展示当前节点的子节点
        // 这么做的原因是因为v-treeview的open-on-click和activable不能共存
        // 如果设置open-on-click属性的话，activeItems会始终为空
        // 所以需要下面这种hack的方式
        const cur_tree_node = this.$refs["treeview"].nodes[node_id]
        if (cur_tree_node) {
          const cur_tree_vnode = cur_tree_node.vnode
          cur_tree_vnode.checkChildren().then(cur_tree_vnode.open())
        }
      },
    },
    computed: {
      currentSelectNode() {
        if (this.activeItems && this.activeItems.length > 0) {
          return this.activeItems[0]
        } else {
          return null
        }
      },
    },
    mounted(){
      // 写入顶层节点
      ArticleCategory.fetch({parent_id:0}, 1, 0).then(res=>{
        this.items = res.results
      })
    },
    methods: {      
      async fetchChildren(item) {
        const res = await ArticleCategory.fetch({parent_id:item.id}, 1, 0)
        const children = res.results
        TreeViewHelper.addChildren(item, children)
        return item
      },
      onAddNew() {
        this.showNodeEditDialog = false
        this.showNodeEditDialog = true
        this.curEditNode = new ArticleCategory()
        if(this.currentSelectNode){
            this.curEditNode.parent_id = this.currentSelectNode.parent_id
        }else{
            this.curEditNode.parent_id = undefined
        }
        
      },
      confirmEdit() {
        let create_node = true
        if (this.curEditNode.id && this.curEditNode.id > 0) {
          // 判断是新增还是修改的情况
          create_node = false
        }
        this.curEditNode.createOrUpdate().then((node) => {
          const treeViewHelper = new TreeViewHelper(this.items)
          // dynamic change item data
          if (!create_node) {
            treeViewHelper.replaceItem(node)
          } else {
            // 新增的情况
            treeViewHelper.insertItem(node)
          }
          this.curEditNode = new ArticleCategory()
          this.showNodeEditDialog = false
        })
      },
      addChildrenNode(item) {
        // 当前节点下新增
        this.curEditNode = new ArticleCategory()
        this.curEditNode.parent_id = item.id
        this.showNodeEditDialog = false
        this.showNodeEditDialog = true
      },
      renameNode(item) {
        // 从目录树传过来的节点重命名
        this.curEditNode = merge(new ArticleCategory(), item)
        this.showNodeEditDialog = false
        this.showNodeEditDialog = true
      },
      
      deleteNode(item) {
        this.$dialog.confirm({
          text: "确定要删除该节点:" + item.name,
          title: "警告",
          waitForResult: true,
          actions: {
            false: {
              text: "取消",
              color: "blue",
            },
            true: {
              text: "确定",
              color: "red",
              handle: () => {
                const item_parent_id = item.parent_id
                const item_id = item.id
                return item.delete().then((res) => {
                  const treeViewHelper = new TreeViewHelper(this.items)
                  treeViewHelper.deleteItem({
                    id: item_id,
                    parent_id: item_parent_id,
                  })
                  return
                })
              },
            },
          },
        })
      },
    },
  }
</script>
